package com.wan.net.config;

import cn.hutool.core.net.NetUtil;

import java.util.Objects;

public final class HostAndPort {
    //本地
    public static final String LOCAL = "127.0.0.1";
    //广播地址
    public static final String BROADCAST = "255.255.255.255";

    private final String host;
    private final int port;

    private HostAndPort(String host, int port){
        this.host = host;
        this.port = port;
    }

    public static HostAndPort of(String host,int port){
        return new HostAndPort(host,port);
    }
    /** 127.0.0.1 */
    public static HostAndPort ofLocal(int port){
        return of(LOCAL,port);
    }
    /** 内网ip */
    public static HostAndPort ofInner(int port){
        return of(NetUtil.getLocalhostStr(),port);
    }

    public static HostAndPort parse(String hostString){
        int lastColon = hostString.lastIndexOf(":");
        String host = hostString.substring(0, lastColon);
        int port = Integer.parseInt(hostString.substring(lastColon + 1));
        return new HostAndPort(host, port);
    }

    public String getHost() {
        return host;
    }

    public int getPort() {
        return port;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        HostAndPort that = (HostAndPort) o;
        return port == that.port && Objects.equals(host, that.host);
    }

    @Override
    public int hashCode() {
        return Objects.hash(host, port);
    }

    @Override
    public String toString() {
        return this.host + ":" + this.port;
    }
}
